package com.trainoo.demo;

import java.io.File;
import java.io.IOException;

import org.junit.Test;

import com.fasterxml.jackson.core.JsonEncoding;
import com.fasterxml.jackson.core.JsonFactory;
import com.fasterxml.jackson.core.JsonGenerator;
import com.fasterxml.jackson.core.JsonParser;
import com.fasterxml.jackson.core.JsonToken;
import com.fasterxml.jackson.databind.JsonNode;
import com.fasterxml.jackson.databind.ObjectMapper;

public class Demo_04_Jackson_DataBind {

	static class MyValue{
		public String name;
		public int age;
		
		@Override
		public String toString() {
			return "MyValue [name=" + name + ", age=" + age + "]";
		}
	}
	
	ObjectMapper mapper = new ObjectMapper(); // create once, reuse
	
	@Test
	public void test01() throws Exception{
		MyValue value = null;
		value = mapper.readValue("{\"name\":\"Bob\", \"age\":13}", MyValue.class);
		System.out.println(value);
		
		mapper.writeValue(new File("data.json"), value);
		
		JsonNode root = mapper.readTree(new File("data.json"));
		String name = root.get("name").asText();
		System.out.println("name = " + name);
		int age = root.get("age").asInt();
		System.out.println(age);
	}
	
	@Test
	public void test02() throws IOException{
		JsonFactory f = mapper.getFactory();
		JsonGenerator g = f.createGenerator(new File("data1.json"), JsonEncoding.UTF8);
		g.writeStartObject();
		g.writeObjectField("message", "hello word");
		g.writeEndObject();
		g.close();
	}
	
	@Test
	public void test03() throws Exception{
		
		JsonFactory f = mapper.getFactory();
		JsonParser parser = f.createParser(new File("data.json"));
		JsonToken token = parser.nextToken();
		while(parser.hasCurrentToken()){
			
			if(token == JsonToken.FIELD_NAME)
				System.out.print(parser.getText() + " = ");
			if(token == JsonToken.VALUE_STRING)
				System.out.println(parser.getText());
			
			token = parser.nextToken();
		}
		parser.close();
	}
}
